package com.michale.framework.config.async.asyncFactory;

import com.michale.common.constants.CommonConstant;
import com.michale.common.domain.operate.LoginInfoEntity;
import com.michale.common.domain.operate.OperateLogEntity;
import com.michale.common.log.LogUtils;
import com.michale.common.utils.Ip.AddressUtils;
import com.michale.common.utils.Ip.IpUtils;
import com.michale.common.utils.Ip.ServletUtils;
import com.michale.common.utils.String.StringUtils;
import com.michale.common.utils.spring.SpringUtils;
import com.michale.system.service.LoginInfoService;
import com.michale.system.service.OperateLogService;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.TimerTask;

/**
 * @author Michale
 * @apiNote 异步工厂（产生任务用）
 */
public class AsyncTask {
    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-AsyncTask");

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息
     * @param args     列表
     * @return 任务task
     */
    public static TimerTask recordLoginInfo(final String username, final String status, final String message,
                                             final Object... args) {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddress(ServletUtils.getRequest());
        return new TimerTask() {
            @Override
            public void run() {
                String address = AddressUtils.getRealAddressByIP(ip);
                StringBuilder s = new StringBuilder();
                s.append(LogUtils.getBlock(ip));
                s.append(address);
                s.append(LogUtils.getBlock(username));
                s.append(LogUtils.getBlock(status));
                s.append(LogUtils.getBlock(message));
                // 打印信息到日志
                sys_user_logger.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                LoginInfoEntity loginInfoEntity = new LoginInfoEntity();
                loginInfoEntity.setUserName(username);
                loginInfoEntity.setIpaddr(ip);
                loginInfoEntity.setLoginLocation(address);
                loginInfoEntity.setBrowser(browser);
                loginInfoEntity.setOs(os);
                loginInfoEntity.setMsg(message);
                // 日志状态
                if (StringUtils.equalsAny(status, CommonConstant.LOGIN_SUCCESS, CommonConstant.LOGOUT, CommonConstant.REGISTER)) {
                    loginInfoEntity.setStatus(CommonConstant.SUCCESS);
                } else if (CommonConstant.LOGIN_FAIL.equals(status)) {
                    loginInfoEntity.setStatus(CommonConstant.FAIL);
                }
                // 插入数据
                int i = SpringUtils.getBean(LoginInfoService.class).insertLoginInfo(loginInfoEntity);
            }
        };
    }

    /**
     * 操作日志记录
     *
     * @param sysOperaLog 操作日志信息
     * @return 任务task
     */
    public static TimerTask recordLog(final OperateLogEntity sysOperaLog) {
        return new TimerTask() {
            @Override
            public void run() {
                // 远程查询操作地点
                sysOperaLog.setOperateLocation(AddressUtils.getRealAddressByIP(sysOperaLog.getOperateIp()));
                SpringUtils.getBean(OperateLogService.class).insertOperable(sysOperaLog);
            }
        };
    }
}
